package com.yboot.stater.websocket.core.api;

import lombok.Getter;
import org.springframework.messaging.simp.SimpMessagingTemplate;

import java.util.List;

/**
 * 消息推送扩展工具类。
 * 指定用户发送消息时候， 订阅开头的是/user/{token}/{topic}
 * <p>
 * 1. 根据用户解析对应的 token
 */
@Getter
public class SimpMessagingEnhanceTemplate {

    private final SimpMessagingTemplate simpMessagingTemplate;

    private final DestinationResolveApi destinationResolveApi;

    public SimpMessagingEnhanceTemplate(SimpMessagingTemplate simpMessagingTemplate, DestinationResolveApi destinationResolveApi) {
        this.simpMessagingTemplate = simpMessagingTemplate;
        this.destinationResolveApi = destinationResolveApi;
    }

    /**
     * 给指定平台、指定订阅者推送消息
     */
    public void convertAndSendToUser(String platform, String userId, String destination, Object payload) {
        List<String> tokens = this.destinationResolveApi.getPlatformSubscriberTokens(platform, userId);
        tokens.forEach(user -> this.simpMessagingTemplate.convertAndSendToUser(user, destination, payload));
    }

    /**
     * 给指定平台、指定订阅者推送消息
     */
    public void convertAndSendToUser(String platform, List<String> userIds, String destination, Object payload) {
        List<String> tokens = this.destinationResolveApi.getPlatformSubscriberTokens(platform, userIds);
        tokens.forEach(user -> this.simpMessagingTemplate.convertAndSendToUser(user, destination, payload));
    }

    /**
     * 给指定订阅者推送消息
     */
    public void convertAndSendToUser(String userId, String destination, Object payload) {
        List<String> tokens = this.destinationResolveApi.getSubscriberTokens(userId);
        tokens.forEach(user -> this.simpMessagingTemplate.convertAndSendToUser(user, destination, payload));
    }

    /**
     * 给指定订阅者推送消息
     */
    public void convertAndSendToUser(List<String> userIds, String destination, Object payload) {
        List<String> tokens = this.destinationResolveApi.getSubscriberTokens(userIds);
        tokens.forEach(user -> this.simpMessagingTemplate.convertAndSendToUser(user, destination, payload));
    }


    /**
     * 发送广播消息
     */
    public void convertAndSend(String destination, Object payload) {
        this.simpMessagingTemplate.convertAndSend(destination, payload);
    }

}
